package com.netty.client;

import java.lang.reflect.Proxy;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.netty.connect.ConnectManage;
import com.netty.discovery.ServiceDiscovery;
import com.netty.proxy.IAsyncObjectProxy;
import com.netty.proxy.ObjectProxy;
//http://www.cnblogs.com/luxiaoxun/p/5272384.html
public class ClientProxy {
	
	private ServiceDiscovery serviceDiscovery;

	private static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(16, 16,
            600L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(65536));
	
	public ClientProxy(ServiceDiscovery serviceDiscovery){
		this.serviceDiscovery = serviceDiscovery;
	}
	/**
	 * 同步代理对象
	 * @param interfaceClass
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <T> T create(Class<T> interfaceClass){
		return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), 
				new Class<?>[]{interfaceClass},
				new ObjectProxy<T>(interfaceClass));
	}
	/**
	 * 异步代理对象
	 * @param interfaceClass
	 * @return
	 */
	public <T> IAsyncObjectProxy createAsync(Class<T> interfaceClass){
		return new ObjectProxy<T>(interfaceClass);
	}
	/**
	 * 处理任务
	 * @param task
	 */
	public static void submit(Runnable task){
		threadPoolExecutor.submit(task);
	}
	
	public void stop(){
		threadPoolExecutor.shutdown();
		serviceDiscovery.stop();
		ConnectManage.getInstance().stop();
	}
}
